package loadresource;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.example.administrator.weipiao.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bean.Movies;
import fragment.MovieFragment;

/**
 * Created by Administrator on 2016/9/10.
 */
public class LoadJsonTask extends AsyncTask<String,Void,List<Movies>> {
    /*//定义回调接口
    private interface OnGetJsonResultListener{
        void onGetJsonResult(List<Movies> result);
    }
    //创建接口对象
    private OnGetJsonResultListener mListener;
    //实例化接口对象
    public LoadJsonTask(OnGetJsonResultListener listener){
        this.mListener = listener;
    }*/
    //定义回调接口
    public interface OnGetJsonResultListener {
        void onGetJsonResult(List<Movies> result);
    }

    private OnGetJsonResultListener mListener;

    private ProgressDialog mDialog;

    public LoadJsonTask(OnGetJsonResultListener context) {
            this.mListener = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected List<Movies> doInBackground(String... params) {
        //下载json
        try {
            byte[] data = HttpUtil.loadData(params[0]);
            ArrayList<Movies> list = new ArrayList<>();
            //解析json
            String json = new String(data);
            JSONObject object = new JSONObject(json);
            JSONArray jsonArray = object.getJSONArray("list");
            for (int i=0;i<jsonArray.length();i++){
                JSONObject obj = jsonArray.getJSONObject(i);
                String logo = obj.getString("logo");
                String name = obj.getString("name");
                String highlight = obj.getString("highlight");
                String grade = obj.getString("grade");
                String actors = obj.getString("actors");
                Movies movies = new Movies(logo,name,highlight,grade,actors);
                list.add(movies);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<Movies> movies) {
        super.onPostExecute(movies);
//        mDialog.dismiss();
        //回调结果
        if(mListener!=null&&movies!=null){
            mListener.onGetJsonResult(movies);
        }
    }
}
